from django.db import models
from user.models import BlogUser
import datetime


# Create your models here.

class Category(models.Model):
    name = models.CharField("博客类别", max_length=30, unique=True)

    def __str__(self):
        return self.name


class Blog(models.Model):
    # 用户被删除，对应的文章也被删除
    author = models.ForeignKey(BlogUser, on_delete=models.CASCADE, related_name="blog",
                               related_query_name="blog", verbose_name="作者")
    # 文章存在禁止直接删除对应的类别
    category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name="博客类别")
    title = models.CharField("博客标题", max_length=40)
    content = models.TextField("博客内容")
    description = models.TextField("博客描述", null=True, blank=True)  # 用于博客列表封面上介绍使用
    # TODO 限制封面图片大小
    cover_picture = models.ImageField(upload_to="cover_pic/", verbose_name="博客封面图片",
                                      null=True, blank=True)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def increase_pv(self, request):
        cookie_key = f'blog_pv_{self.pk}'  # unique for a single blog
        if not request.COOKIES.get(cookie_key):
            # 有效访问
            BlogPV.increase(self, valid=True)
            DailyPV.increase(valid=True)
        else:
            # 无效访问
            BlogPV.increase(self, valid=False)
            DailyPV.increase(valid=False)
        return cookie_key

    def __str__(self):
        return f'<blog-{self.pk}>: {self.title}'

    class Meta:
        ordering = ['-create_time']


class BlogPV(models.Model):
    # 一个博客的访问量, page view
    click_num = models.PositiveIntegerField(default=0, editable=False)  # 点击量
    valid_click_num = models.PositiveIntegerField(default=0, editable=False)  # 有效访问量
    blog = models.OneToOneField(Blog, on_delete=models.CASCADE, related_name="pv",
                                verbose_name="对应博客")

    @classmethod
    def increase(cls, blog, valid=False):
        """
        @params valid: 是否是有效访问量
        """
        blog_pv, _ = cls.objects.get_or_create(blog=blog)
        blog_pv.click_num += 1
        if valid:
            blog_pv.valid_click_num += 1
            blog_pv.save(update_fields=['valid_click_num', 'click_num'])
        else:
            blog_pv.save(update_fields=['click_num'])


class DailyPV(models.Model):
    # 每日博客访问量
    date = models.DateField(auto_now_add=True, unique=True)
    click_num = models.PositiveBigIntegerField(default=0)  # 点击量
    valid_click_num = models.PositiveIntegerField(default=0)  # 有效访问量

    @classmethod
    def increase(cls, valid=False):
        """
        @params valid: 是否是有效访问量
        """
        today = datetime.date.today()  # get local date
        daily_pv, _ = cls.objects.get_or_create(date=today)
        daily_pv.click_num += 1
        if valid:
            daily_pv.valid_click_num += 1
            daily_pv.save(update_fields=['valid_click_num', 'click_num'])
        else:
            daily_pv.save(update_fields=['click_num'])
